package com.zsc.oj.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zsc.oj.annotation.AuthCheck;
import com.zsc.oj.annotation.TestLog;
import com.zsc.oj.common.BaseResponse;
import com.zsc.oj.common.DeleteRequest;
import com.zsc.oj.common.ErrorCode;
import com.zsc.oj.common.ResultUtils;
import com.zsc.oj.constant.UserConstant;
import com.zsc.oj.exception.BusinessException;
import com.zsc.oj.exception.ThrowUtils;
import com.zsc.oj.judge.JudgeService;
import com.zsc.oj.judge.strategy.JudgeContext;
import com.zsc.oj.mapper.QuestionSubmitMapper;
import com.zsc.oj.model.dto.question.*;
import com.zsc.oj.model.dto.questionSubmit.*;
import com.zsc.oj.model.entity.AcceptQuestion;
import com.zsc.oj.model.entity.Question;
import com.zsc.oj.model.entity.QuestionSubmit;
import com.zsc.oj.model.entity.User;
import com.zsc.oj.model.enums.JudgeInfoMessageEnum;
import com.zsc.oj.model.enums.QuestionSubmitLanguageEnum;
import com.zsc.oj.model.vo.*;
import com.zsc.oj.service.AcceptQuestionService;
import com.zsc.oj.service.QuestionService;
import com.zsc.oj.service.QuestionSubmitService;
import com.zsc.oj.service.UserService;
import lombok.extern.slf4j.Slf4j;
import com.zsc.oj.manager.AIManager;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 题目接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@RestController
@RequestMapping("/question")
@Slf4j
public class QuestionController {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    @Resource
    private QuestionSubmitService questionSubmitService;

    @Resource
    private JudgeService judgeService;

    @Resource
    private AcceptQuestionService acceptQuestionService;

    @Resource
    private AIManager aiManager;

    @Resource
    private QuestionSubmitMapper questionSubmitMapper;

    // region 增删改查

    /**
     * 创建题目
     *
     * @param questionAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addQuestion(@RequestBody QuestionAddRequest questionAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(questionAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        BeanUtils.copyProperties(questionAddRequest, question);
        // 数据校验
        questionService.validQuestion(question, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        question.setUserId(loginUser.getId());

        //将judgecase和judgeconfig写入数据库
        List<JudgeCase> judgeCase = questionAddRequest.getJudgeCase();
        if(judgeCase != null){
            question.setJudgeCase(JSONUtil.toJsonStr(judgeCase));
        }
        JudgeConfig judgeConfig = questionAddRequest.getJudgeConfig();
        if(judgeConfig != null){
            question.setJudgeConfig(JSONUtil.toJsonStr(judgeConfig));
        }
        List<String> tags = questionAddRequest.getTags();
        if(tags != null){
            question.setTags(JSONUtil.toJsonStr(tags));
        }

        // 写入数据库
        boolean result = questionService.save(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newQuestionId = question.getId();
        return ResultUtils.success(newQuestionId);
    }

    /**
     * 删除题目
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestion.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = questionService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新题目（仅管理员可用）
     *
     * @param questionUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestion(@RequestBody QuestionUpdateRequest questionUpdateRequest) {
        if (questionUpdateRequest == null || questionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        BeanUtils.copyProperties(questionUpdateRequest, question);
        // 数据校验
        questionService.validQuestion(question, false);
        // 判断是否存在
        long id = questionUpdateRequest.getId();
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);

        //添加judgecase和judgeconfig
        List<JudgeCase> judgeCase = questionUpdateRequest.getJudgeCase();
        if(judgeCase != null){
            String judgeCaseStr = JSONUtil.toJsonStr(judgeCase);
            question.setJudgeCase(judgeCaseStr);
        }
        JudgeConfig judgeConfig = questionUpdateRequest.getJudgeConfig();
        if(judgeConfig != null){
            String judgeConfigStr = JSONUtil.toJsonStr(judgeConfig);
            question.setJudgeConfig(judgeConfigStr);
        }

        // 操作数据库
        boolean result = questionService.updateById(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取题目（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionVO> getQuestionVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Question question = questionService.getById(id);
        ThrowUtils.throwIf(question == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(questionService.getQuestionVO(question, request));
    }

    /**
     * 分页获取题目列表（仅管理员可用）
     *
     * @param questionQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Question>> listQuestionByPage(@RequestBody QuestionQueryRequest questionQueryRequest) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 查询数据库
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        return ResultUtils.success(questionPage);
    }

    /**
     * 分页获取题目列表（封装类）
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                               HttpServletRequest request) {
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 分页获取当前登录用户创建的题目列表
     *
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listMyQuestionVOByPage(@RequestBody QuestionQueryRequest questionQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(questionQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        questionQueryRequest.setUserId(loginUser.getId());
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }

    /**
     * 编辑题目（给用户使用）
     *
     * @param questionEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editQuestion(@RequestBody QuestionEditRequest questionEditRequest, HttpServletRequest request) {
        if (questionEditRequest == null || questionEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        Question question = new Question();
        BeanUtils.copyProperties(questionEditRequest, question);
        // 数据校验
        questionService.validQuestion(question, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = questionEditRequest.getId();
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestion.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = questionService.updateById(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    //--------------------------- 题目提交部分------------------------------------------------

    /**
     * 创建题目提交
     *
     * @param questionSubmitAddRequest
     * @param request
     * @return
     */
    @PostMapping("/questionSubmit/add")
    public BaseResponse<String> addQuestionSubmit(@RequestBody QuestionSubmitAddRequest questionSubmitAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(questionSubmitAddRequest == null, ErrorCode.PARAMS_ERROR);
        // 数据校验
//        questionSubmitService.validQuestionSubmit(questionSubmit, true);
        String language = questionSubmitAddRequest.getLanguage();
        String code = questionSubmitAddRequest.getCode();
        Long questionId = questionSubmitAddRequest.getQuestionId();

        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if(languageEnum == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"编程语言错误");
        }
        if(StringUtils.isBlank(code)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"提交的代码不能为空");
        }
        if(questionId == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目id不能为空");
        }

        QuestionSubmit questionSubmit = new QuestionSubmit();
        BeanUtils.copyProperties(questionSubmitAddRequest, questionSubmit);

        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        questionSubmit.setUserId(loginUser.getId());
        // 写入数据库
        boolean result = questionSubmitService.save(questionSubmit);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newQuestionSubmitId = questionSubmit.getId();

        judgeService.doJudge(newQuestionSubmitId);

        QuestionSubmit finishQuestionSubmit = questionSubmitService.getById(newQuestionSubmitId);
        String judgeInfo = finishQuestionSubmit.getJudgeInfo();
        JudgeInfo info = JSONUtil.toBean(judgeInfo, JudgeInfo.class);
        String message = info.getMessage();

        //若用户回答正确，将该题目id记录到acceptQuestionId
        List<AcceptQuestion> list = acceptQuestionService.list();
        Set<Long> acceptSet = list.stream().map(AcceptQuestion::getQuestionId).collect(Collectors.toSet());
        if(message.equals(JudgeInfoMessageEnum.ACCEPTED.getValue()) && !acceptSet.contains(questionId)){
            AcceptQuestion acceptQuestion = new AcceptQuestion();
            acceptQuestion.setQuestionId(questionId);
            acceptQuestion.setUserId(loginUser.getId());
            acceptQuestionService.save(acceptQuestion);
        }

        return ResultUtils.success(message);
    }

    /**
     * 创建题目并由AI判题
     *
     * @param questionSubmitAddRequest
     * @param request
     * @return
     */
    @PostMapping("/questionSubmit/add/ai")
    public BaseResponse<String> addQuestionSubmitByAI(@RequestBody QuestionSubmitAddRequest questionSubmitAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(questionSubmitAddRequest == null, ErrorCode.PARAMS_ERROR);
        // 数据校验
//        questionSubmitService.validQuestionSubmit(questionSubmit, true);
        String language = questionSubmitAddRequest.getLanguage();
        String code = questionSubmitAddRequest.getCode();
        Long questionId = questionSubmitAddRequest.getQuestionId();

        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if(languageEnum == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"编程语言错误");
        }
        if(StringUtils.isBlank(code)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"提交的代码不能为空");
        }
        if(questionId == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目id不能为空");
        }

        QuestionSubmit questionSubmit = new QuestionSubmit();
        BeanUtils.copyProperties(questionSubmitAddRequest, questionSubmit);

        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        questionSubmit.setUserId(loginUser.getId());

        Question question = questionService.getById(questionId);

        String AIResult = aiManager.doStableRequest(QUESTION_JUDGE_SYSTEM_PROMPT, userPrompt(code, language, question));
        int start = AIResult.indexOf("{");
        int end = AIResult.indexOf("}");
        String resultString = AIResult.substring(start, end + 1);

        questionSubmit.setStatus(2);
        questionSubmit.setJudgeInfo(resultString);
        boolean save = questionSubmitService.save(questionSubmit);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"题目提交失败");
        }

        JudgeInfo info = JSONUtil.toBean(resultString, JudgeInfo.class);
        String message = info.getMessage();

        return ResultUtils.success(message);
    }

    /**
     * 删除题目提交
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/questionSubmit/delete")
    public BaseResponse<Boolean> deleteQuestionSubmit(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        QuestionSubmit oldQuestionSubmit = questionSubmitService.getById(id);
        ThrowUtils.throwIf(oldQuestionSubmit == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldQuestionSubmit.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = questionSubmitService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新题目提交（仅管理员可用）
     *
     * @param questionSubmitUpdateRequest
     * @return
     */
    @PostMapping("/questionSubmit/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestionSubmit(@RequestBody QuestionSubmitUpdateRequest questionSubmitUpdateRequest) {
        if (questionSubmitUpdateRequest == null || questionSubmitUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        QuestionSubmit questionSubmit = new QuestionSubmit();
        BeanUtils.copyProperties(questionSubmitUpdateRequest, questionSubmit);
        // 数据校验
        questionSubmitService.validQuestionSubmit(questionSubmit, false);
        // 判断是否存在
        long id = questionSubmitUpdateRequest.getId();
        QuestionSubmit oldQuestionSubmit = questionSubmitService.getById(id);
        ThrowUtils.throwIf(oldQuestionSubmit == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = questionSubmitService.updateById(questionSubmit);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取题目提交（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/questionSubmit/get/vo")
    public BaseResponse<QuestionSubmitVO> getQuestionSubmitVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        QuestionSubmit questionSubmit = questionSubmitService.getById(id);
        ThrowUtils.throwIf(questionSubmit == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(questionSubmitService.getQuestionSubmitVO(questionSubmit, request));
    }

    /**
     * 分页获取题目提交列表（仅管理员可用）
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @PostMapping("/questionSubmit/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<QuestionSubmit>> listQuestionSubmitByPage(@RequestBody QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        long current = questionSubmitQueryRequest.getCurrent();
        long size = questionSubmitQueryRequest.getPageSize();
        // 查询数据库
        Page<QuestionSubmit> questionSubmitPage = questionSubmitService.page(new Page<>(current, size),
                questionSubmitService.getQueryWrapper(questionSubmitQueryRequest));
        return ResultUtils.success(questionSubmitPage);
    }

    /**
     * 分页获取题目提交列表（封装类）
     *
     * @param questionSubmitQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/questionSubmit/list/page/vo")
    public BaseResponse<Page<QuestionSubmitVO>> listQuestionSubmitVOByPage(@RequestBody QuestionSubmitQueryRequest questionSubmitQueryRequest,
                                                                           HttpServletRequest request) {
        long current = questionSubmitQueryRequest.getCurrent();
        long size = questionSubmitQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<QuestionSubmit> questionSubmitPage = questionSubmitService.page(new Page<>(current, size),
                questionSubmitService.getQueryWrapper(questionSubmitQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionSubmitService.getQuestionSubmitVOPage(questionSubmitPage, request));
    }

    /**
     * 分页获取当前登录用户创建的题目提交列表
     *
     * @param questionSubmitQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/questionSubmit/my/list/page/vo")
    public BaseResponse<Page<QuestionSubmitVO>> listMyQuestionSubmitVOByPage(@RequestBody QuestionSubmitQueryRequest questionSubmitQueryRequest,
                                                                             HttpServletRequest request) {
        ThrowUtils.throwIf(questionSubmitQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        questionSubmitQueryRequest.setUserId(loginUser.getId());
        long current = questionSubmitQueryRequest.getCurrent();
        long size = questionSubmitQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<QuestionSubmit> questionSubmitPage = questionSubmitService.page(new Page<>(current, size),
                questionSubmitService.getQueryWrapper(questionSubmitQueryRequest));
        // 获取封装类
        return ResultUtils.success(questionSubmitService.getQuestionSubmitVOPage(questionSubmitPage, request));
    }

    /**
     * 编辑题目提交（给用户使用）
     *
     * @param questionSubmitEditRequest
     * @param request
     * @return
     */
    @PostMapping("/questionSubmit/edit")
    public BaseResponse<Boolean> editQuestionSubmit(@RequestBody QuestionSubmitEditRequest questionSubmitEditRequest, HttpServletRequest request) {
        if (questionSubmitEditRequest == null || questionSubmitEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        QuestionSubmit questionSubmit = new QuestionSubmit();
        BeanUtils.copyProperties(questionSubmitEditRequest, questionSubmit);
        // 数据校验
        questionSubmitService.validQuestionSubmit(questionSubmit, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = questionSubmitEditRequest.getId();
        QuestionSubmit oldQuestionSubmit = questionSubmitService.getById(id);
        ThrowUtils.throwIf(oldQuestionSubmit == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldQuestionSubmit.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = questionSubmitService.updateById(questionSubmit);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }
    // endregion

    public static final String QUESTION_GENERATE_SYSTEM_PROMPT = "你是一位严谨的出题专家并且熟悉许多国内的OJ判题系统(如：leetcode)，我会给你如下信息：\n" +
            "```\n" +
            "题目标题，\n" +
            "判题用例的输入用例个数\n" +
            "判题用例的输出用例个数\n" +
            "```\n" +
            "\n" +
            "请你根据上述信息，按照以下步骤来出题：\n" +
            "1.题目内容必须符合上述信息的题目标题的要求来描述并且尽量详细。\n" +
            "2.你所给出的判题用例的输入用例经过你所给出的答案运行后必须等于判题用例的输出用例。\n" +
            "3.下面是一段示例，假如给出的题目标题是两数之和，判题用例的输入用例个数为2，判题用例的输出用例个数为3，生成以下json格式的字符串。注意：要严格按照下面的json格式输出\n" +
            "```\n" +
            "[\n" +
            "\t{\n" +
            "\t  \"answer\": \"public class Main {public static void main(String[] args) {int a = Integer.parseInt(args[0]);int b = Integer.parseInt(args[1]);int sum = a+b;System.out.println(sum);}}\",\n" +
            "\t  \"content\": \"请你定义两个变量并返回两数之和\",\n" +
            "\t  \"judgeCase\": [\n" +
            "\t    {\n" +
            "\t      \"input\": \"1 2\",\n" +
            "\t      \"output\": \"3\"\n" +
            "\t    },\n" +
            "\t    {\n" +
            "\t      \"input\": \"2 3\",\n" +
            "\t      \"output\": \"5\"\n" +
            "\t    }\n" +
            "\t  ],\n" +
            "\t  \"judgeConfig\": {\n" +
            "\t    \"memoryLimit\": 0,\n" +
            "\t    \"stackLimit\": 0,\n" +
            "\t    \"timeLimit\": 0\n" +
            "\t  },\n" +
            "\t  \"tags\": [\"简单\"],\n" +
            "\t  \"title\": \"两数之和\"\n" +
            "\t}\n" +
            "]\n" +
            "\n" +
            "```\n" +
            "title是题目标题，tags是题目的标签根据你所给出的题目内容和判题用例和判题配置所给出对应的标签，judgeConfig是判题配置，memoryLimit是内存限制，stackLimit是堆栈限制，timeLimit是时间限制，judgeCase是判题用例，input是输入用例，output是输出用例，answer是这道题目的答案，content是题目的内容\n" +
            "4.最后只需要按照上面三点的要求返回json格式字符串。\n" +
            "5.你所生成的答案必须是JAVA语言并且类名必须为Main并且要按照JAVA语法进行换行\n" +
            "6.你所生成的content题目内容可以使用markdown语法使用户更加明确题目的内容是什么";

    public String getUserPrompt(String title,int inputNum,int outputNum){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(title).append("\n");
        stringBuilder.append(inputNum).append("\n");
        stringBuilder.append(outputNum).append("\n");
        return stringBuilder.toString();
    }


    /**
     * 使用AI生成题目
     * @param questionAIRequest
     * @return
     */
    @PostMapping("/add/ai")
    public BaseResponse<List<QuestionAIVO>> addQuestionByAi(@RequestBody QuestionAIRequest questionAIRequest){
        if(questionAIRequest == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }

        String title = questionAIRequest.getTitle();
        Integer inputNum = questionAIRequest.getInputNum();
        Integer outputNum = questionAIRequest.getOutputNum();

        if(StringUtils.isBlank(title)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"标题不能为空");
        }
        if(inputNum == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"输入用例数不能为空");
        }
        if(outputNum == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"输出用例数不能为空");
        }

        String userPrompt = getUserPrompt(title, inputNum, outputNum);

        //调用ai生成结果
        String result = aiManager.doStableRequest(QUESTION_GENERATE_SYSTEM_PROMPT, userPrompt);

        //因为ai生成的json会标注为json，存在多余的字段
        int begin = result.indexOf("[");
        int end = result.lastIndexOf("]");
        String json = result.substring(begin, end + 1);

        //把json转成列表
        List<QuestionAIVO> questionList = JSONUtil.toList(json, QuestionAIVO.class);
        return ResultUtils.success(questionList);

    }

    /**
     * 获取ES中的题目
     * @param questionQueryRequest
     * @param request
     * @return
     */
    @PostMapping("list/es")
    public BaseResponse<Page<QuestionVO>> listEsQuestion(@RequestBody QuestionQueryRequest questionQueryRequest,HttpServletRequest request){
        int pageSize = questionQueryRequest.getPageSize();
        if(pageSize >= 200){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Page<Question> questionPage = questionService.searchFromEs(questionQueryRequest);
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage,request));
    }

    public static final String QUESTION_JUDGE_SYSTEM_PROMPT = "你是一位严谨的编程判题专家，熟悉各种编程语言和熟悉国内OJ判题系统（如：leetcode）并且拥有丰富判题经验。我会给你如下信息：\n" +
            "```\n" +
            "题目名称，\n" +
            "题目内容，\n" +
            "判题用例的输入用例和对应的判题用例的输出用例\n" +
            "时间限制\n" +
            "内存限制\n" +
            "堆栈限制\n" +
            "编程语言\n" +
            "用户输入的代码\n" +
            "```\n" +
            "\n" +
            "请你根据上述信息，按照以下步骤来对用户进行评价：\n" +
            "1. 运行对应编程语言的用户输入的代码，根据给出的判题用例的输入用例和判题用例的输出用例，判断用户输入的代码是否符合要求。只有当运行后用户输入的代码符合用例要求并且运行时消耗的时间、消耗的内存和运行后的堆栈必须小于所给的时间限制，内存限制，堆栈限制才能判定为正确。同时你也可以增加判题的输入用例和对应符合要求的输出用例来判断题目用户的答案是否满足题目要求。\n" +
            "2. 运行用户输入的代码的方式由很多种，例如用户输入的代码是java语言，可以先将用户输入的代码保存为文件，可以使用命令：\"javac -encoding utf-8 文件\" 对用户输入的代码进行编译，可以使用命令：\"java -Dfile.encoding=UTF-8 -cp 编译后的文件 Main 判题用例的输入用例\" 对应编译后的文件运行，输出的结果与对应的输出用例相比较来判断用户是否回答正确。同时你也可以模拟一个真实的判题环境进行判题，并且调用常见的监控工具估算出大致程序运行的消耗内存和消耗时间。\n" +
            "3. 严格按照下面的 json 格式输出判题结果，消耗内存，消耗时间，不需要多余的分析内容与假设过程只需要返回json格式的判题结果、运行时消耗内存、运行时消耗时间即可。判题结果例如运行用户输入的代码时编译错误，则判题结果是Compile Error，如果是运行错误则判题结果是Runtime Error，如果编译运行没有问题但是输出结果不符合要求则判题结果为Wrong Answer，如果符合要求则判题结果为Accepted，以此类推。消耗内存为运行用户输入的代码消耗的内存。消耗时间为运行用户输入的代码消耗的时间。\n" +
            "\n" +
            "```\n" +
            "{\"message\": \"判题结果\", \"memory\": \"消耗内存\", \"time\": \"消耗时间\"}\n" +
            "```\n" +
            "4. 返回格式必须为 JSON 对象\n" +
            "5. 参照上面我给出的例子，返回的内容只需是 json 格式的判题结果、运行用户代码消耗的内存、运行用户代码消耗的时间，并且返回的 JSON 对象不能包含注释，因为 JSON 不支持注释，并且必须要调用或使用常见的监控大致模拟估算出运行用户代码消耗的内存和运行用户代码消耗的时间。";

    public String userPrompt(String code,String language,Question question){
        String config = question.getJudgeConfig();
        String questionCase = question.getJudgeCase();
//        JudgeCase judgeCase = JSONUtil.toBean(questionCase, JudgeCase.class);
        JudgeConfig judgeConfig = JSONUtil.toBean(config, JudgeConfig.class);
        Long memoryLimit = judgeConfig.getMemoryLimit();
        Long timeLimit = judgeConfig.getTimeLimit();
        Long stackLimit = judgeConfig.getStackLimit();
        String title = question.getTitle();
        String content = question.getContent();

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(title).append("\n");
        stringBuilder.append(content).append("\n");
        stringBuilder.append(questionCase).append("\n");
        stringBuilder.append(timeLimit).append("\n");
        stringBuilder.append(memoryLimit).append("\n");
        stringBuilder.append(stackLimit).append("\n");
        stringBuilder.append(language).append("\n");
        stringBuilder.append(code).append("\n");

        return stringBuilder.toString();
    }

    /**
     * 获取每道题目的答题数
     * @return
     */
    @GetMapping("get/question/num")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<List<QuestionSubmitNum>> getQuestionSubmitNum(){
        List<QuestionSubmitNum> questionSubmit = questionSubmitMapper.getQuestionSubmit();
        return ResultUtils.success(questionSubmit);
    }

    /**
     * 获取题目对应的编程语言
     */
    @GetMapping("get/language/num")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<List<QuestionLanguageNum>> getQuestionLanguageNum(Long questionId){
        if(questionId == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<QuestionLanguageNum> questionLanguageNum = questionSubmitMapper.getQuestionLanguageNum(questionId);
        return ResultUtils.success(questionLanguageNum);
    }


}
